package org.sdnstproject.interlayer.OF13Protocal;

import java.util.HashMap;
import org.projectfloodlight.openflow.types.U32;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class FuEchoReply {
	private static final Logger log = LoggerFactory.getLogger(FuRoleReply.class);
    public byte version = (byte)4;
    public byte type = (byte)3;
    public short length = (short)8;
    public long xid = 0x0L;//需要dummyswitch设置
	public long data = 0L;//原本是byte[] data;byte[] DEFAULT_DATA = new byte[0];但一般为0,length=8
	
	public FuEchoReply() {
		
	}
	    	
    public FuEchoReply setField(String field, String value) {
		switch (field) {
		case "version":
			this.version = Byte.parseByte(value);
			break;
		case "type":
			this.type = Byte.parseByte(value);
			break;
		case "length":
			this.length = Short.parseShort(value);
			break;
		case "xid":
			this.xid = Long.parseLong(value);
			break;
		case "data":
			this.data = Long.parseLong(value);
			break;
		}
		return this;
	}
    
    public HashMap<String, String> FuEchoReplyFields = new HashMap<String, String>() {
		{
			put("version","byte");
			put("type","byte");
			put("length","short");
			put("xid","long");
			put("data", "long");
		}
    };
    
	public ByteBuf writeTo() {
		ByteBuf bb = Unpooled.directBuffer();
        int startIndex = bb.writerIndex();
        // fixed value property version = 4
        bb.writeByte(version);
        // fixed value property type = 3
        bb.writeByte(type);
        // length is length of variable message, will be updated at the end
        int lengthIndex = bb.writerIndex();
        bb.writeShort(length);

        bb.writeInt(U32.t(xid));
        if(data != 0) {
        	bb.writeLong(data);
        }
        if(length == 8) {
        	// update length field
        	int length = bb.writerIndex() - startIndex;
        	bb.setShort(lengthIndex, length);
        }
        return bb;
    }
	@Override
    public String toString() {
        StringBuilder b = new StringBuilder("OFEchoReplyVer13(");
        b.append("version=").append(version);
        b.append(", ");
        b.append("type=").append(type);
        b.append(", ");
        b.append("length=").append(length);
        b.append(", ");
        b.append("xid=").append(xid);
        b.append(", ");
        b.append("data=").append(data);
        b.append(")");
        return b.toString();
    }
}
